package server;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;

import server.Preferences.ConversationWindow;
import server.Preferences.SortBy;

/**
 * <h1>Class DBManager</h1>
 * 
 * Provides access to the application database.
 * Is implemented following the Singleton pattern.
 * 
 * @author Tomas
 * @date March 6 2009
 * @ modified by Jim March 10 2009
 */
public class DBManager {

	/**
	 * Single instance of the class
	 */
	private static DBManager instance = null;
	
	protected final String driver = "com.mysql.jdbc.Driver"; 
	protected final String propertiesFile = "DB.properties";
    protected String dirserver = "";
    protected String db = "";
    protected String login = "";
    protected String password = "";
    protected String url = "";
	
	/**
	 * Default constructor. Initializes the single instance of the class.
	 */
	private DBManager(){

		Properties prop = new Properties();
		InputStream file = null;
		
		try{
			file = new FileInputStream(propertiesFile);
			prop.load(file);
		}catch(Exception e){
			LogException.getInstance().logException(e);
		}
		
		if(prop != null){
			dirserver = prop.getProperty("server");
			db = prop.getProperty("db");
			login = prop.getProperty("login");
			password = prop.getProperty("password");
			url = "jdbc:mysql://" + dirserver + "/" + db;
		}
	}
	
	/**
	 * Obtains the single instance of the class.
	 * @return
	 */
	public static DBManager getInstance(){
		
		if(instance == null){
			instance = new DBManager();
		}
		
		return instance;
	}
	
	/**
	 * Opens a connection to the database.
	 * 
	 * @return
	 * 		Connection to the database if the operation was successful.
	 * 		Otherwise, null.
	 */
	private Connection initConnection(){
		
		try{
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url,login,password);
            connection.setAutoCommit(false);
            return connection;
        }catch(Exception e){
        	LogException.getInstance().logException(e);
        }
        
        return null;
	}
	
	/**
	 * Closes a connection to the database.
	 * 
	 * @param conn
	 * 		Connection to be closed.
	 */
	private void closeConnection(Connection conn){
		
		try{
			conn.commit();
			conn.close();
		}catch(Exception e){
			LogException.getInstance().logException(e);
		}
		
	}
	
	
	/**
	 * Authenticates a user of the system by querying the database to check
	 * if s/he exists and his/her password is correct.
	 * 
	 * @param username
	 * 		User's name who needs to authenticate in the system.
	 * @param password
	 * 		User's encrypted password
	 * @return
	 * 		An instance of the class Person if the authentication was correct.
	 * 		Otherwise, null;
	 */
	public synchronized Person authenticate(String username, String password){
		
		Connection c = initConnection();
		try{
			String checkName = "SELECT username FROM person" +
					//" WHERE username = ? AND password = ?";
				  " WHERE username = '" +username+ "' AND password = '"+ password+"'";
			Statement stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery(checkName);
			if(rs.next() == false){
				closeConnection(c);
				stmt.close();
				return null;
			}
			else{
				return (new Person(username));
			}
		}
		catch(Exception e){
			System.out.println("authenticate exceiption "+ e.getMessage());
			LogException.getInstance().logException(e);
		}		
		return null;
		
	}
	
	/**
	 * Creates a new account for a user.
	 * 
	 * @param username
	 * 		User's desired name in the system.
	 * @param password
	 * 		User's desired password to enter into the system.
	 * @return
	 * 		Boolean value telling if the operation was successful:
	 * 		<ul>
	 * 			<li>True: the username was not used and the account was created.</li>
	 * 			<li>False: the account couldn't be created.</li>
	 * 		</ul>
	 */
	public synchronized boolean createAccount(String username, String password){
		
		// query the DB to check if the username is being used.
		// If not, create a new account for that user
		try
		{	
			Connection c = initConnection();
			String checkName = "SELECT username FROM person" +
					" WHERE username = '" +username+"'";
			Statement stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery(checkName);	
			if(rs.next() == false){
				String newAccount = "INSERT INTO person";
				newAccount += " VALUES ('"+ username+"','"+password+"')";
				stmt.executeUpdate(newAccount);
				closeConnection(c);
				stmt.close();
				return true;
			}		
			else
			{
				System.out.println(rs.getString(1)+" has account");
				closeConnection(c);
				stmt.close();
			}		
		}
		catch(Exception e)
		{
			LogException.getInstance().logException(e);
		}
		return false;		
	}
	
	/**
	 * Deletes an account. It needs the password in order to be secure and
	 * prevent malicious users deleting other people's accounts.
	 * 
	 * @param username
	 * 		User's name who wants to delete his/her account.
	 * @param password
	 * 		User's password.
	 * @return
	 * 		Boolean value indicating if the operation was successful or not:
	 * 		<ul>
	 * 			<li>True: the account was deleted and it is not accessible anymore.</li>
	 * 			<li>False: the account couldn't be deleted.
	 * 		</ul>
	 */
	public synchronized boolean deleteAccount(String username, String password){
		
		// check the database looking the account and if the username
		// and password match, delete the account.
		try
		{
			if( authenticate(username, password) != null){
				String delete = "DELETE FROM person WHERE username = '" + username +"'"+
				" AND password = '" + password +"'";
				Connection c = initConnection();
				Statement stmt = c.createStatement();
				stmt.executeUpdate(delete);
				closeConnection(c); stmt.close();
				System.out.println("account for "+username+" deleted");
				return true;
			}
		}
		catch(Exception e){
			LogException.getInstance().logException(e);
		}
		return false;
		
	}
	
	/**
	 * Creates a group in the user's buddy list.
	 * 
	 * @param username
	 * 		User's name who wants to create the group.
	 * @param groupID
	 * 		ID for the group to be created.
	 * @param groupName
	 * 		Name for the group to be created.
	 * @return
	 * 		Boolean value indicating if the operation was successful or not.
	 */
	//public synchronized boolean createGroup(String username, String groupID, String groupName){
	  public synchronized boolean createGroup(String username, String groupName){
		// add group to the database.
		try
		{
			String insert = "INSERT INTO groups "
				+ "VALUES ('"+ groupName +"','"+ username+"')";
			Connection c = initConnection();
			Statement stmt = c.createStatement();
			stmt.executeUpdate(insert);
			closeConnection(c); stmt.close();
			System.out.println("group "+ groupName +" created");
			return true;		
		}
		catch(Exception e){
			System.out.println("error in create group "+ e.getMessage());
			LogException.getInstance().logException(e);
		}
		return false;
	}
	
	/**
	 * Deletes a group for a user. The group shouldn't contain any members. Otherwise, those
	 * buddies may be lost. 
	 * 
	 * 
	 * @param username
	 * 		User's name whose group must be deleted.
	 * @param groupName
	 * 		Group to delete
	 * @return
	 * 		Boolean value indicating if the operation was successful.
	 */
	//public synchronized boolean deleteGroup(String username, String groupID){
	public synchronized boolean deleteGroup(String username, String groupName){
		try
		{
			//check if there are buddyname in groupmember table; if not, delete the group 
			// from groups
			String checkGroup = "SELECT * FROM groupmember WHERE groupname = '"+groupName+"'" +
			" AND username = '"+ username +"'";
			Connection c = initConnection();
			Statement stmnt = c.createStatement();
			ResultSet rs = stmnt.executeQuery(checkGroup);
			if( rs.next() == false){// the group has no members so delete
				String delete = "DELETE FROM groups WHERE groupname = '"+groupName + "'" +
				" AND owner = '"+ username + "'";
				Statement stmt = c.createStatement();
				stmt.executeUpdate(delete);
				closeConnection(c); stmt.close();
				System.out.println("group " + groupName+ " deleted");
				return true;
			}
		}
		catch(Exception e){
			System.out.println("error in delete group "+ groupName);
			LogException.getInstance().logException(e);
		}
		return false;
		
	}
	
	/**
	 * Initializes the buddylist
	 * @param username User's name who wants to add the buddy
	 * @param buddyname The buddy to add
	 * @param groupname The groupname to add to
	 * @return Boolean value indicates if the operation was successful
	 */
	public synchronized boolean initializeBuddyList(String username, String buddyName,
			String groupName){
		Connection c = initConnection();
		try
		{
			String insert = "INSERT INTO groupmember VALUES (' "+groupName+
			"','"+ username + "','" + buddyName + "')";
			c.createStatement().executeUpdate(insert);
			System.out.println("known buddy added to group");
			closeConnection(c); 
			System.out.println("initializeBuddyList successful");
			return true;		
		}
		catch(Exception e){
			System.out.println(" error in initializeBuddyList "+e.getMessage());
			LogException.getInstance().logException(e);			
		}
		return false;
	}
	/**
	 * Adds a buddy to a group. (groupmember table: *groupname, username fk ref to person, buddyname)
	 * 
	 * @param username
	 * 		User's name who wants to add the buddy.
	 * @param buddyName
	 * 		Buddy's name
	 * @param groupName
	 * 		Add the buddy to this group
	 * @return
	 * 		Boolean value indicating if the operation was successful or not.
	 */
	//public synchronized boolean addBuddyToGroup(String username, String buddyName, String groupID){
	public synchronized boolean addBuddyToGroup(String username, String buddyName, String groupName){	
		// add buddy to group. This can be tricky:
		// 1.- We must check the group is created.
		// 2.- We must check if the buddy is already in another group.
		//     In such case, we don't have to wait for confirmation to add them.
		// 3.- If they are not friends, we have to include this in a temporary table
		//     and wait for confirmation.
		Connection c = initConnection();
		try
		{
			String checkGroup = "SELECT groupname FROM groups WHERE " +
					"groupname = '" + groupName +"'";//groupname is primary key
			Statement stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery(checkGroup);
			if( rs.next() != false){
				//check if buddy in another group
				String knownBuddy = "SELECT buddyname FROM groupmember WHERE "+
				"username = '"+username+"' AND buddyname = '"+buddyName+"'";
				ResultSet rs2 = c.createStatement().executeQuery(knownBuddy);
				if( rs2.next() != false){ // buddy is in another group so add him to this group
					String insert = "INSERT INTO groupmember VALUES (' "+groupName+
					"','"+ username + "','" + buddyName + "')";
					c.createStatement().executeUpdate(insert);
					System.out.println("known buddy added to group");
					closeConnection(c); 
				}
				else{ // add the buddyname to the pendingmembers table
					String pending = "INSERT INTO pendingmembers VALUES ('" + username +
							"','" +buddyName+ "','"+ groupName + "')";
					c.createStatement().executeUpdate(pending);
					closeConnection(c); 
					System.out.println("buddy added to pendingmembers");
					return false;
				}
				
			}
		}
		catch(Exception e){
			System.out.println(" error in addBuddyToGroup "+e.getMessage());
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
	}
	
	/**
	 * Confirms a pending request to become friends
	 * 
	 * @param sender
	 * 		Person who confirms the request
	 * @param confirmed
	 * 		Person who is confirmed as a friend
	 * @param group
	 * 		Sender's group where the confirmed is to be added.
	 * @return
	 * 		Boolean value indicating if the operation was successful or nor.
	 */
	public synchronized boolean confirmBuddyToGroup(String sender, String confirmed, String group){
		
		String sql = "INSERT INTO groupmember VALUES (" +
			"'" + group + "', " +
			"'" + sender + "', " +
			"'" + confirmed + "')";
		
		try{
			Connection c = initConnection();
			Statement insert = c.createStatement();
			insert.executeUpdate(sql);
			insert.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 * Removes a buddy from a group
	 * 
	 * @param username
	 * 		User's name who wants to remove his/her contact.
	 * @param buddyName
	 * 		Buddy's name to be removed.
	 * @param groupName
	 * 		Delete the buddy from this group
	 * @return
	 */
	//public synchronized boolean deleteBuddyFromGroup(String username, String buddyName, String groupID){
	public synchronized boolean deleteBuddyFromGroup(String username, String buddyName, String groupName){
		try{
			Connection c = initConnection();
			String deleteBuddy = "DELETE FROM groupmember WHERE username = '"+username+ 
			"' AND groupname = '"+groupName+"' AND buddyname = '" +buddyName+ "'";
			int i = c.createStatement().executeUpdate(deleteBuddy);
			closeConnection(c); 
			if( i > 0){
				System.out.println("deletBuddyFromGroup successful");
			}
			else{
				System.out.println("deleteBuddyFromGroup not deleting");
			}
			return true;
		}
		catch(Exception e){
			System.out.println("error in deleteBuddyFromGroup "+ e.getMessage());
			LogException.getInstance().logException(e);
		}	
		return false;		
	}
	
	/**
	 * Obtains the buddy list for a certain user. 
	 * 
	 * @param username
	 * 		User's name who wants his/her list back.
	 * @return
	 * 		BuddyList object for the user.
	 */
	public synchronized BuddyList getBuddyList(String username){
		
		//build the buddy list for the user.
		/*String getBuddies = "SELECT buddyname FROM groupmember "+
		   "WHERE username = '"+ username + "'";
		BuddyList bl = new BuddyList();
		Group group = new Group();
		try
		{
			Connection c = initConnection();
			ResultSet rs = c.createStatement().executeQuery(getBuddies);
			while(rs.next()){
				group.addMember(new Person(rs.getString(1)));
			}
			bl.addGroup(group);
			closeConnection(c);
			return bl;
		}
		catch(Exception e){
			System.out.println("error in get buddy " + e.getMessage());
			LogException.getInstance().logException(e);
		}
		return null;*/
		
		BuddyList bl = new BuddyList();
		
		String getGroups = "SELECT groupname FROM groups " + 
			"WHERE owner = '" + username + "'";
		try{
			Connection c = initConnection();
			Statement groupStatement = c.createStatement();
			ResultSet groupSet = groupStatement.executeQuery(getGroups);
			
			while(groupSet.next()){
				String groupname = groupSet.getString("groupname");
				Group g = new Group(groupname);
				
				String getMembers = "SELECT buddyname FROM groupmember " +
					"WHERE username = '" + username +"' AND " +
					"groupname = '" + groupname + "'";
				Statement memberStatement = c.createStatement();
				ResultSet members = memberStatement.executeQuery(getMembers);
				
				while(members.next()){
					String membername = members.getString("buddyname");
					Person p = new Person(membername);
					g.addMember(p);
				}
				
				bl.addGroup(g);
				memberStatement.close();
			}
			groupStatement.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return bl;
		
	}
	
	/**
	 * Obtains the user's preferences. If there are no preferences, returns
	 * the default preferences.
	 * 
	 * @param username
	 * 		User's name who wants his/her preferences back.
	 * @return
	 * 		Preferences for the user (if they exist) or default preferences.
	 * 		If any error happens, it returns null.
	 */
	public synchronized Preferences getPreferences(String username){
		
		Preferences pref = new Preferences();
		
		String getPref = "SELECT * FROM preferences " +
			"WHERE username = '" + username + "'";
		
		try{
			Connection c = initConnection();
			Statement st = c.createStatement();
			ResultSet prefSet = st.executeQuery(getPref);
			
			if(prefSet.next()){
				int timeAway = prefSet.getInt("timeawaymode");
				boolean sound = (prefSet.getInt("sound") == 1);
				boolean icon = (prefSet.getInt("icon") == 1);
				boolean grouped = (prefSet.getInt("grouped") == 1);
				boolean showoffline = (prefSet.getInt("showoffline") == 1);
				String path = prefSet.getString("default_path");
				int history = prefSet.getInt("historydays");
				int sort = prefSet.getInt("sortcriteria");
				int window = prefSet.getInt("conversation_window");
				SortBy sortCrit = SortBy.NAME;
				ConversationWindow conv = ConversationWindow.INDIVIDUAL;
				
				switch(sort){
					case 0:
						sortCrit = SortBy.NAME;
					case 1:
						sortCrit = SortBy.GROUP;
				}
				
				switch(window){
					case 0:
						conv = ConversationWindow.INDIVIDUAL;
					case 1:
						conv = ConversationWindow.TABBED;
				}
				
				pref.setTimeAwayMode(timeAway);
				pref.setSound(sound);
				pref.setIcon(icon);
				pref.setGrouped(grouped);
				pref.setShowOffline(showoffline);
				pref.setDefaultPath(path);
				pref.setHistoryDays(history);
				pref.setSortCriteria(sortCrit);
				pref.setConvWindow(conv);
			}
			
			st.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return pref;
		
	}
	
	/**
	 * Saves the user's preferences.
	 * 
	 * @param username
	 * 		User's name whose preferences need to be stored.
	 * @param pref
	 * 		User's preferences to be stored.
	 * @return
	 * 		Boolean value indicating if the operation was successful.
	 */
	public synchronized boolean storePreferences(String username, Preferences pref){
		
		boolean sound = pref.isSoundActive();
		boolean icon = pref.isIconActive();
		boolean grouped = pref.isGrouped();
		boolean showoffline = pref.isShowOffline();
		int timeaway = (int) pref.getTimeAwayMode();
		int historyDays = pref.getHistoryDays();
		String path = pref.getDefaultPath();
		int sort = 0;
		int conv = 0;
		
		switch(pref.getSortCriteria()){
			case NAME:
				sort = 0;
			case GROUP:
				sort = 1;
		}
		
		switch(pref.getConvWindow()){
			case INDIVIDUAL:
				conv = 0;
			case TABBED:
				conv = 1;
		}
		
		try{
			String checkPref = "SELECT * FROM preferences WHERE "+
				"username = '" + username + "'";
			
			Connection c = initConnection();
			Statement checkSt = c.createStatement();
			ResultSet check = checkSt.executeQuery(checkPref);
			
			if(check.next()){
				System.out.println("inside update preferences");
				String updateSQL = "UPDATE preferences SET " +
					"timeawaymode = '" + timeaway + "', " +
					"sound = '" + (sound ? 1 : 0) + "', " +
					"sortcriteria = '" + sort + "', " +
					"icon = '" + (icon ? 1 : 0) + "', " +
					"grouped = '" + (grouped ? 1 : 0) + "', " +
					"showoffline = '" + (showoffline ? 1 : 0) + "', " +
					"conversation_window = '" + conv + "', " +
					"default_path = '" + path + "', " +
					"historydays = '" + historyDays +"' "+
					"WHERE username = '" + username + "'";
				Statement update = c.createStatement();
				update.executeUpdate(updateSQL);
				update.close();
			}else{
				String insertSQL = "INSERT INTO preferences VALUES ('" +
					username + "',' " +
					timeaway + "', '" +
					(sound ? 1 : 0) + "',' " +
					sort + "',' " +
					(icon ? 1 : 0) + "', '" +
					(grouped ? 1 : 0) + "',' " +
					(showoffline ? 1 : 0) + "', '" +
					conv + "',' " +
					path + "', '" +
					historyDays + "')";
				Statement insert = c.createStatement();
				insert.executeUpdate(insertSQL);
				insert.close();
			}
			checkSt.close();
			closeConnection(c);
		}catch(Exception e){
			System.out.println("Exception in insert preferences: "+ e.getMessage());
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 * Obtains the people who tried to talk to the user while s/he was offline.
	 *  
	 * @param username
	 * 		User's name who wants to get the messages.
	 * @return
	 * 		Iterator over the names of people who tried to talk to the user.
	 * 		If any error happens, it returns null.
	 */
	public synchronized Iterator<String> getOfflineMessageAuthors(String username){
		
		ArrayList<String> authors = new ArrayList<String>();
		
		try{
			Connection c = initConnection();
			String sql = "SELECT DISTINCT sender FROM offlinemessage WHERE " +
				"receiver = '" + username  + "'";
			Statement st = c.createStatement();
			ResultSet authorSet = st.executeQuery(sql);
			
			while(authorSet.next()){
				authors.add(authorSet.getString("sender"));
			}
			
			st.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return authors.iterator();
		
	}
	
	/**
	 * Obtains the messages sent by a certain user.
	 * 
	 * @param username
	 * 		Receiver of the messages
	 * @param sender
	 * 		Sender of the messages
	 * @return
	 * 		Iterator over the messages.
	 * 		If any errors happen, it returns null.
	 */
	public synchronized Iterator<String> getOfflineMessages(String username, String sender){
		
		ArrayList<String> messages = new ArrayList<String>();
		
		try{
			Connection c = initConnection();
			String sql = "SELECT message FROM offlinemessage WHERE " +
				"sender = '" + sender + "' AND " +
				"receiver = '" + username + "' " +
				"ORDER BY mssg_date";
			Statement st = c.createStatement();
			ResultSet messageSet = st.executeQuery(sql);
			
			while(messageSet.next()){
				messages.add(messageSet.getString("message"));
			}
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return messages.iterator();
		
	}
	
	/**
	 * Deletes all the offline messages for a certain user.
	 * 
	 * @param username
	 * 		User whose offline messages are going to be deleted.
	 * @return
	 * 		Boolean value indicating if the operation was successful or not.
	 */
	public synchronized boolean removeOfflineMessages(String username){
		
		String deleteOff = "DELETE FROM offlinemessage WHERE receiver = '" + username +"'";
		
		try{
			Connection c = initConnection();
			Statement deleteSt = c.createStatement();
			deleteSt.executeUpdate(deleteOff);
			deleteSt.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 * Adds a new offline message to be delivered when the user goes online.
	 * 
	 * @param sender
	 * 		Sender of the message.
	 * @param receiver
	 * 		Receiver of the message.
	 * @param message
	 * 		Offline message.
	 * @return
	 * 		Boolean value indicating if the operation was successful or not.
	 */
	public synchronized boolean addOfflineMessage(String sender, String receiver, String message){
		
		String addMessage = "INSERT INTO offlinemessage VALUES (" +
			"'" + sender + "', " +
			"'" + receiver + "', " +
			"NOW(), " +
			"'" + message + "')";
		
		try{
			Connection c = initConnection();
			Statement insert = c.createStatement();
			insert.executeUpdate(addMessage);
			insert.close();
			closeConnection(c);
		}catch(Exception e){
			System.out.println("some error in addOfflineMessage "+e.getMessage());
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 * Rejects a pending request.
	 * 
	 * @param rejecter
	 * 		User who doesn't want to become friends.
	 * @param waiting
	 * 		User waiting for confirmation
	 * @return
	 * 		Boolean value indicating if the operation was successful or not.
	 */
	public synchronized boolean rejectFriend(String rejecter, String waiting){
		
		String remove = "DELETE FROM pendingmembers WHERE " +
			"username = '" + waiting + "' AND " +
			"pendingname = '" + rejecter + "'";
		
		try{
			Connection c = initConnection();
			Statement insert = c.createStatement();
			insert.executeUpdate(remove);
			insert.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
	}
	
	public synchronized String getPendingGroup(String username, String pending){
		
		String pendingSQL = "SELECT groupname FROM pendingmembers WHERE " + 
			"username = '" + username +"' AND " +
			"pendingname = '" + pending + "'";
		
		String group = null;
		
		try{
			Connection c = initConnection();
			Statement st = c.createStatement();
			ResultSet result = st.executeQuery(pendingSQL);
			
			if(result.next()){
				group = result.getString("groupname");
			}
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return group;
	}
	
	public synchronized boolean deletePending(String username, String pendingname, String groupname){
		
		String remove = "DELETE FROM pendingmembers WHERE " + 
			"username = '" + username + "' AND " +
			"pendingname = '" + pendingname + "' AND " +
			"groupname = '" + groupname + "'";
		
		try{
			Connection c = initConnection();
			Statement insert = c.createStatement();
			insert.executeUpdate(remove);
			insert.close();
			closeConnection(c);
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return false;
		}
		
		return true;
		
	}
	
	public synchronized Iterator<String> pendingRequests(String username){
		
		String pendingSQL = "SELECT username FROM pendingmembers WHERE " +
			"pendingname = '" + username + "'";
		
		ArrayList<String> pendings = new ArrayList<String>();
		
		try{
			Connection c = initConnection();
			Statement st = c.createStatement();
			ResultSet result = st.executeQuery(pendingSQL);
			
			while(result.next()){
				pendings.add(result.getString("username"));
			}
		}catch(Exception e){
			LogException.getInstance().logException(e);
			return null;
		}
		
		return pendings.iterator();
	}
}
